package service

import (
	"duoke/internal/dao"
	"duoke/model"
	"duoke/tables"
	"duoke/utils/orm"
	"github.com/gin-gonic/gin"
)

var CourseMenu = new(courseMenuService)

type courseMenuService struct{}

// List 获取列表 不分页
func (s *courseMenuService) List(c *gin.Context, id int) ([]tables.CourseMenu, error) {
	accountR, _ := Request.Account(c)
	var course []tables.CourseMenu
	err := dao.CourseMenu.Ctx(c).OrderDesc("id").Where("acid=? and parent_id=?", accountR.Id, id).Scan(&course)
	if err != nil {
		return nil, err
	}
	return course, nil
}

// Save 保存
func (s *courseMenuService) Save(c *gin.Context, req *tables.CourseMenu) error {
	accountR, _ := Request.Account(c)
	req.Acid = accountR.Id
	_, err := dao.CourseMenu.Ctx(c).Save(&req)
	if err != nil {
		return err
	}
	return nil
}

func (s *courseMenuService) Del(c *gin.Context, id int) error {
	_, err := dao.CourseMenu.Ctx(c).Where("id=?", id).Delete()
	if err != nil {
		return nil
	}
	return nil
}
func (s *courseMenuService) WxMenu(c *gin.Context) ([]*model.CourseMenu, error) {
	accountR, _ := Request.Account(c)
	var nodes []*model.CourseMenu
	err := orm.Db.Where("acid = ?", accountR.Id).Find(&nodes)
	if err != nil {
		return nil, err
	}
	nodeMap := make(map[int]*model.CourseMenu)
	var roots []*model.CourseMenu
	// 先将所有节点存入 map
	for _, node := range nodes {
		nodeMap[node.Id] = node
	}
	// 构建树结构
	for _, node := range nodes {
		if node.ParentId == 0 {
			roots = append(roots, node)
		} else {
			parent, exists := nodeMap[node.ParentId]
			if exists {
				parent.Children = append(parent.Children, node)
			}
		}
	}
	return roots, nil
}
